var res;
function Car(){
    this.set = (id,c,component)=>{
        this[id] = c
        component.setState({})
    }
    this.calc = ()=>{
        var number = 0;
        var price = 0;
        for(var k in this){
            if(k=="coupon"||typeof this[k]=="function")continue;
            number+=this[k].male+this[k].famale;
            var data = this[k].data
            var coupon = this[k].coupon&&this[k].coupon.value||0
            var p = this[k].male*data.male_price+this[k].famale*data.famale_price - coupon
            price+=p>0?p:0;
        }
        sessionStorage.buyCar = JSON.stringify(res)
        return {
            number,
            price
        }
    }
    this.getCar = ()=>{
        var cars = []
        for(var k in this){
            if(k=="coupon"||typeof this[k]=="function")continue;
            cars.push(this[k])
        }
        return cars
    }
}

res = {
    "once":new Car(),
    "week":new Car()
}

res.calc = function(){
    var a = res.once.calc()
    var b = res.week.calc()
    return {
        number:a.number+b.number,
        price:a.price+b.price
    }
}

res.getCar = function(){
    return res.once.getCar().concat(res.week.getCar())
}

res.existCoupon = function(item){
    var li = res.getCar()
    for(var i=0;i<li.length;i++){
        if(li[i].coupon&&li[i].coupon.id==item.id)return true;
    }
    return false;
}

res.save = function(){
    sessionStorage.buyCar = JSON.stringify(res)
}

var tmp;
if(sessionStorage.buyCar){
    eval("tmp = "+sessionStorage.buyCar)
    for(var k in tmp){
        if(k!="once"&&k!="week"){
            res[k] = tmp[k]
        }
    }
    extend("once")
    extend("week")
}

function extend(a){
    var t = tmp[a]
    for(var k in t){
        if(typeof t[k]=="function")continue;
        res[a][k] = t[k]
    }
}

module.exports = res
